import Vue from 'vue'
import Router from 'vue-router'

import home from './home' // 首页
import errorPage from './error-page' // 错误页面
import usersManage from './users-manage'
import moduleRouter from './module-router'
import verificationRule from './verification-rule'
import serviceRouter from './service-router'
import store from '@/store'

const Login = () => import(/* webpackChunkName: "common" */ '@/pages/login')
const Layout = () => import(/* webpackChunkName: "common" */ '@/pages/layout')
const NotFound = () => import(/* webpackChunkName: "common" */ '@/pages/not-found')
const EcrfDetail = () => import(/* webpackChunkName: "common" */ '@/pages/ecrf-detail')

Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: Login,
    },
    {
      path: '/',
      component: Layout,
      redirect: { name: 'Home' },
      children: [
        ...Object.values(home),
        ...Object.values(usersManage),
        ...Object.values(moduleRouter),
        ...Object.values(verificationRule),
        ...Object.values(serviceRouter),
      ],
    },
    ...Object.values(errorPage),
    {
      name: 'ecrf-detail',
      path: '/ecrf-detail',
      component: EcrfDetail,
    },
    {
      name: '404',
      path: '/404',
      component: NotFound,
    },
    // 此处需至于最底部，保证404路由的重定向
    {
      path: '*',
      redirect: { name: '404' },
    },
  ],
})

router.beforeEach((to, from, next) => {
  // 清除端口名
  if (from.name === 'EDC项目管理') {
    if (to.name !== '数据库版本') {
      store.commit('layoutHeader/removeState')
    }
  }
  // 清除端口名
  if (to.name === '受试者汇总') {
    store.commit('layoutHeader/removeState')
  }
  if (from.name === '项目中心') {
    if (to.name === 'EDC项目管理') {
      // 设置端口名
      store.commit('layoutHeader/setState', 'Builder')
    }
  }
  next()
})

export default router
